/*
 * @(#)companyServiceImpl.java 2013-4-10 ����01:36:55 Order
 */
package com.dingtalk.dingbotmgr.service.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.dingtalk.dingbotmgr.dao.BaseDao;
import com.dingtalk.dingbotmgr.dao.TaskDao;
import com.dingtalk.dingbotmgr.message.Message;
import com.dingtalk.dingbotmgr.model.ChatBot;
import com.dingtalk.dingbotmgr.model.ChatBotMessage;
import com.dingtalk.dingbotmgr.model.Task;
import com.dingtalk.dingbotmgr.service.ChatBotMessageService;
import com.dingtalk.dingbotmgr.service.TaskService;
import com.dingtalk.dingbotmgr.task.ChatBotMessageJob;
import com.dingtalk.dingbotmgr.task.QuartzManager;
import org.springframework.stereotype.Component;

/**
 * companyServiceImpl
 *
 * @author wang
 * @version 1.0
 */
@Component("taskService")
public class TaskServiceImpl extends BaseServiceImpl<Task> implements TaskService {

    @Resource(name = "taskDao")
    private TaskDao taskDao;

    @Resource(name = "chatBotMessageService")
    private ChatBotMessageService chatBotMessageService;

    @Override
    protected BaseDao<Task> getBaseDao() {
        return taskDao;
    }

    private void addJob(Task task) {
        Map<String, Object> map = new HashMap<>();
        map.put("message", task.getChatBotMessage().getMessage());
        QuartzManager.addJob(String.valueOf(task.getId()), ChatBotMessageJob.class, task.getCronExpression(), map);
    }

    @PostConstruct
    public void init() {
        List<Task> taskList = list();
        for (Task task : taskList) {
            addJob(task);
        }
    }

    @Override
    public void saveOrUpdate(Task task, Message message, List<Integer> chatBotIdList) {
        Set<ChatBot> chatBotSet = new HashSet<>();
        for (Integer id : chatBotIdList) {
            ChatBot chatBot = new ChatBot();
            chatBot.setId(id);
            chatBotSet.add(chatBot);
        }
        task.setChatBotSet(chatBotSet);
        ChatBotMessage chatBotMessage = task.getChatBotMessage();
        if (chatBotMessage == null) {
            chatBotMessage = new ChatBotMessage();
            chatBotMessage.setJsonStr(message.toJsonString());
            chatBotMessageService.saveOrUpdate(chatBotMessage);
            task.setChatBotMessage(chatBotMessage);
        }
        taskDao.saveOrUpdate(task);
        addJob(task);
    }
}
